package com.thib.htstvremote;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

import com.thib.models.Entrie;
import com.thib.models.Finished;


public class Requests {
	
	private String mServer = "http://legros.hd.free.fr:9981";
	private CharSequence mUser = "xbmc";
	private CharSequence mPass = "xbmc";
	private String jsonText = null;
	public CharSequence url = null;
	private Map<String, String> map;
	ArrayList<Entrie> entrieList = null;
	ArrayList<Finished> arrayRecorder = null;
	public Requests()
	{
	
	}
	
	
	public void getChannelsTags()
	{
		
		this.url = "/channeltags";
		map = new HashMap<String, String>();
		map.put("op", "listTags");
		jsonText = this.pushUrl(this.url,true);
		
		ObjectMapper objectMapper = new ObjectMapper();
        JsonFactory  jsonFactory = new JsonFactory();
        try
        {
	        JsonParser jp = jsonFactory.createJsonParser(jsonText);
	        com.thib.models.Entries e = objectMapper.readValue(jp, com.thib.models.Entries.class);
	        entrieList = e.get("entries");
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
	}
	
	public void getChannels()
	{
		this.url = "/channels";
		map = new HashMap<String, String>();
		map.put("op", "list");
		jsonText = this.pushUrl(this.url,true);
		
		ObjectMapper objectMapper = new ObjectMapper();
        JsonFactory  jsonFactory = new JsonFactory();
        try
        {
	        JsonParser jp = jsonFactory.createJsonParser(jsonText);
	        com.thib.models.Entries e = objectMapper.readValue(jp, com.thib.models.Entries.class);
	        entrieList = e.get("entries");
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
	}
	
	public void getUpcoming()
	{
		this.url = "/dvrlist_upcoming";
		String jsonText 			=  this.pushUrl(this.url,true);
		JsonFactory  jsonFactory 	= new JsonFactory();
		ObjectMapper objectMapper 	= new ObjectMapper();
		arrayRecorder 				= new ArrayList<Finished>();
		try
        {
			JsonParser jParser = jsonFactory.createJsonParser(jsonText);
			JsonNode input = objectMapper.readTree(jParser);
			JsonNode results = input.get("entries");
			arrayRecorder = objectMapper.readValue(results, TypeFactory.collectionType(ArrayList.class, Finished.class));
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
	}
	
	
	public void getFinished()
	{
		this.url = "/dvrlist_finished";
		String jsonText 			=  this.pushUrl(this.url,true);
		JsonFactory  jsonFactory 	= new JsonFactory();
		ObjectMapper objectMapper 	= new ObjectMapper();
		arrayRecorder 				= new ArrayList<Finished>();
		try
        {
			JsonParser jParser = jsonFactory.createJsonParser(jsonText);
			JsonNode input = objectMapper.readTree(jParser);
			JsonNode results = input.get("entries");
			arrayRecorder = objectMapper.readValue(results, TypeFactory.collectionType(ArrayList.class, Finished.class));
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
		
	}
	
	public void getFailed()
	{
		this.url = "/dvrlist_failed";
		String jsonText 			=  this.pushUrl(this.url,true);
		JsonFactory  jsonFactory 	= new JsonFactory();
		ObjectMapper objectMapper 	= new ObjectMapper();
		arrayRecorder 				= new ArrayList<Finished>();
		try
        {
			JsonParser jParser = jsonFactory.createJsonParser(jsonText);
			JsonNode input = objectMapper.readTree(jParser);
			JsonNode results = input.get("entries");
			arrayRecorder = objectMapper.readValue(results, TypeFactory.collectionType(ArrayList.class, Finished.class));
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
		
		
		
	}
	
	public void getEpg(int start)
	{
		this.url = "/epg";
		map = new HashMap<String, String>();
		map.put("start", ""+start);
		int lilit = start +20;
		map.put("limit", ""+lilit);
		//channel:TF1
		//tag:GR1
		//contenttype:16
		String jsonText 			=  this.pushUrl(this.url,true);
		JsonFactory  jsonFactory 	= new JsonFactory();
		ObjectMapper objectMapper 	= new ObjectMapper();
		arrayRecorder 				= new ArrayList<Finished>();
		try
        {
			JsonParser jParser = jsonFactory.createJsonParser(jsonText);
			JsonNode input = objectMapper.readTree(jParser);
			JsonNode results = input.get("entries");
			arrayRecorder = objectMapper.readValue(results, TypeFactory.collectionType(ArrayList.class, Finished.class));
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
		
	}
	
	public boolean removeFinishedRecord(int recordId)
	{
		this.url = "/dvr";
		map = new HashMap<String, String>();
		map.put("entryId",""+recordId);
		map.put("op", "deleteEntry");
		
		
		String jsonText 			=  this.pushUrl(this.url,false);
		JsonFactory  jsonFactory 	= new JsonFactory();
		ObjectMapper objectMapper 	= new ObjectMapper();
		arrayRecorder 				= new ArrayList<Finished>();
		try
        {
			JsonParser jParser = jsonFactory.createJsonParser(jsonText);
			JsonNode input = objectMapper.readTree(jParser);
			JsonNode results = input.get("success");
			
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
		
		return true;
		
	}
	
	public boolean removeRecord(int recordId)
	{
		this.url = "/dvr";
		map = new HashMap<String, String>();
		map.put("op", "cancelEntry");
		map.put("entryId",""+recordId);
		
		String jsonText 			=  this.pushUrl(this.url,false);
		JsonFactory  jsonFactory 	= new JsonFactory();
		ObjectMapper objectMapper 	= new ObjectMapper();
		arrayRecorder 				= new ArrayList<Finished>();
		try
        {
			JsonParser jParser = jsonFactory.createJsonParser(jsonText);
			JsonNode input = objectMapper.readTree(jParser);
			JsonNode results = input.get("success");
			
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
		
		return true;
		
	}
	
	public boolean recordEpg(int ppgmId)
	{
		this.url = "/dvr";
		map = new HashMap<String, String>();
		map.put("op", "recordEvent");
		map.put("eventId",""+ppgmId);
		map.put("config_name","");
		String jsonText 			=  this.pushUrl(this.url,true);
		JsonFactory  jsonFactory 	= new JsonFactory();
		ObjectMapper objectMapper 	= new ObjectMapper();
		arrayRecorder 				= new ArrayList<Finished>();
		try
        {
			JsonParser jParser = jsonFactory.createJsonParser(jsonText);
			JsonNode input = objectMapper.readTree(jParser);
			JsonNode results = input.get("success");
			
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
		
		return true;
		
	}
	
	public String pushUrl(CharSequence url, boolean post)
	{
		String jsonText = "";
		        try
		        {
		        	try
		            {
		            	
		                 HttpClient httpclient = new DefaultHttpClient();
		                 	                 
		                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		                 if(this.map != null && this.map.size() > 0)
		                 for(Entry<String, String> entry : this.map.entrySet()) {
		                	    String cle = entry.getKey();
		                	    String valeur = entry.getValue();
		                	    nameValuePairs.add(new BasicNameValuePair(cle, valeur));
		                	}
		                 HttpResponse response = null;
		                 HttpPost httppost = new HttpPost(mServer+url);
			                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));		 
			                 httppost.addHeader(BasicScheme.authenticate(
			                		 new UsernamePasswordCredentials(mUser.toString(), mPass.toString()),
			                		 "UTF-8", false));		                 
			                response = httpclient.execute(httppost);
		                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		                jsonText = readAll(reader);
		            } catch (ClientProtocolException e) {
		            // TODO
		            	e.printStackTrace();
		            } catch (IOException e) {
		            // TODO
		            	e.printStackTrace();
		            }
		        }
		        catch (Exception e)
		        {
		        	String str = e.toString();
		        	
		            e.printStackTrace();
		        }
		return jsonText;
	}
	
	private static String readAll(Reader rd) throws IOException {
	    StringBuilder sb = new StringBuilder();
	    int cp;
	    while ((cp = rd.read()) != -1) {
	      sb.append((char) cp);
	    }
	    return sb.toString();
	  }
}
